package jp.co.kayo.android.twittertimeline;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.json.JSONArray;
import org.json.JSONObject;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;

public class Utils {
	public static final String SCREEN_NAME="yokmama";
	public static final String LATEST_TIMELINE = "key.latesttimeline";
	
	public static final DateFormat _dateFormat =  new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
	public static final DateFormat _dispFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.JAPANESE);
	
    public static void resetTimeline(Context context){
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        Editor editor = pref.edit();
        editor.putString(LATEST_TIMELINE, "");
        editor.commit();
    }
    
    public static Drawable getImageDrawable(String url) {
        try {
            InputStream is = (InputStream) new URL(url).openStream();
            Drawable d = Drawable.createFromStream(is, "src");
            return d;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
	public static String getJSONString(String url) throws MalformedURLException, IOException{

        BufferedReader in = null;
        try{
            // 接続します
            URLConnection con = new URL(url).openConnection();
            // 入力ストリームを取得
            in = new BufferedReader(new InputStreamReader(con
                    .getInputStream(), "UTF-8"));
    
            // 一行ずつ読み込みます
            StringBuffer json = new StringBuffer();
            String line = null;
            while ((line = in.readLine()) != null) {
                // 表示します
                json.append(line);
            }
            
            return json.toString();
        }
        finally{
            if(in!=null){
                try {
                    in.close();
                } catch (Exception e) {}
            }
        }
	}
	
	public static String getTimeLine(Context context){
	    //二度読み防止処理
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		String timeline =pref.getString(LATEST_TIMELINE, "");
		if(timeline==null || timeline.length()<1){
			BufferedReader in = null;
			try{
    			timeline = getJSONString("http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+SCREEN_NAME);
    			
    			Editor editor = pref.edit();
    			editor.putString(LATEST_TIMELINE, timeline);
    			editor.commit();
			}
			catch(Exception e){
				Logger.e("getTimeline", e);
			}
			finally{
				if(in!=null){
					try {
						in.close();
					} catch (Exception e) {}
				}
			}
		}
		return timeline;
	}
	
	public static Date getCreatedAt(String created_at){
		if(!isEmpty(created_at)){
    		try {
    			Date date = _dateFormat.parse(created_at);
    			Calendar cal = Calendar.getInstance();
    			cal.setTime(date);
    			//cal.add(Calendar.HOUR, 9);
    			return cal.getTime();
    		} catch (ParseException e) {
    		}
		}
		return null;
	}
	
	private static boolean isEmpty(String o){
		if(o!=null){
			if(o.length() != 0){
				return false;
			}
		}
		return true;
	}
	
	public static Profile getProfile(){
		BufferedReader in = null;
		try{
            String json = getJSONString("http://api.twitter.com/1/users/show.json?screen_name="+SCREEN_NAME);
	
			JSONObject obj = new JSONObject(json);
			Profile profile = new Profile();
			profile.setImageurl(obj.getString("profile_image_url"));
			profile.setName(obj.getString("name"));
			profile.setStatuses_count(obj.getString("statuses_count"));
			return profile;
		}
		catch(Exception e){
			Logger.e("getImageURL", e);
		}
		finally{
			if(in!=null){
				try {
					in.close();
				} catch (Exception e) {}
			}
		}
		
		return null;
	}
}
